#include "utilitiesFunction.h"

using namespace std;

void utilitiesFunction::writeXML(cv::Mat m, const char* filename){
	
	/*ofstream fout(filename);

    if(!fout)
    {
        cout<<"File Not Opened"<<endl;  return;
    }

    for(int i=0; i<m.rows; i++)
    {
        for(int j=0; j<m.cols; j++)
        {
            fout<<m.at<float>(i,j)<<",";
        }
        fout<<endl;
    }

    fout.close();*/

	cv::FileStorage fs(filename, cv::FileStorage::WRITE);
	fs <<"siftDictionary"<<m;
	fs.release();
}

std::vector<std::string> &utilitiesFunction::split(const std::string &s, char delim, std::vector<std::string> &elems){
	std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> utilitiesFunction::split(const std::string &s, char delim){
	std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}

std::vector<double> utilitiesFunction::convertStringVectorToDouble(std::vector<std::string> str){
	vector<double> elems;
	for(int i = 0 ; i < str.size(); i++){
		string temp = str.at(i);
		//double d_temp = atof(temp.c_str());
		double d_temp;
		char *str = new char[temp.length() + 1];
		strcpy(str,temp.c_str());
		sscanf(str, "%lf", &d_temp);
		
		elems.push_back(d_temp);
		
		delete str;
	}
	return elems;
}

cv::Mat utilitiesFunction::readXML(const char* filename){
	/*ifstream infile(filename);
	string line;
	std::vector<std::vector<double>> m_d_str;
	
	if (infile.is_open())
	{
		while (getline(infile, line))
		{
			vector<std::string> v_str = split(line, ',');
			vector<double> d_str = convertStringVectorToDouble(v_str);
			m_d_str.push_back(d_str);

			for(int i = 0; i < d_str.size() ; i++){
				cout << d_str.at(i) << " , " ;
			}
			cout << endl;
		}
		infile.close();
	}

	cv::Mat result(m_d_str.size(), m_d_str.at(0).size(), CV_64FC1);
	for(int i=0; i<result.rows; ++i){
		for(int j=0; j<result.cols; ++j){
			result.at<double>(i, j) = m_d_str.at(i).at(j);
		}
	}*/

	cv::Mat result;
	cv::FileStorage fs(filename, cv::FileStorage::READ);
	fs["siftDictionary"] >> result;
	fs.release();

	return result;
}